#include <gst/gst.h>
#include <glib.h>

static gboolean bus_call(GstBus *bus, GstMessage *msg, gpointer data)
{
    GMainLoop *loop = (GMainLoop *) data;
    switch (GST_MESSAGE_TYPE(msg)) {
        case GST_MESSAGE_EOS:
            g_print("End of stream\n");
            g_main_loop_quit(loop);
            break;
        case GST_MESSAGE_ERROR: {
            gchar *debug;
            GError *error;
            gst_message_parse_error(msg, &error, &debug);
            g_free(debug);
            g_printerr("Error: %s\n", error->message);
            g_error_free(error);
            g_main_loop_quit(loop);
            break;
        }
        default:
            break;
    }

    return TRUE;
}


static void on_pad_added(GstElement *element, GstPad *pad, gpointer data)
{
    GstPad *sinkpad;
    GstElement *decoder = (GstElement *)data;
    g_print("Dynamic pad created, linking demuxter/decoder\n");
    sinkpad = gst_element_get_static_pad(decoder, "sink");
    gst_pad_link(pad, sinkpad);
    gst_object_unref(sinkpad);
}


int main (int argc, char *argv[])
{
    GMainLoop *loop;
    GstElement *pipeline, *source, *sink;
    GstBus *bus;

    /* init GStreamer */
    gst_init(&argc, &argv);
    
    loop = g_main_loop_new(NULL, FALSE);
    
    /* create pipeline */
    pipeline = gst_pipeline_new("my_pipeline");
    source = gst_element_factory_make("v4l2src","webcamsrc");
    sink = gst_element_factory_make("xvimagesink", "x11sink");
    if (!pipeline || !source || !sink ) {
        g_printerr("One of element could not be created. Exiting...\n");
        return -1;
    }
    
    /* we add a message handle */
    bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
    gst_bus_add_watch(bus, bus_call, loop);
    gst_object_unref(bus);

    /* we add all elements into the pipeline */
    gst_bin_add_many(GST_BIN(pipeline), source, sink, NULL);

    /* we linke the elements together */
    gst_element_link(source, sink);

    /* Set the pipeline to "playing" state */
    g_print("Now show video on X-11 viewer\n");
    gst_element_set_state(pipeline, GST_STATE_PLAYING);
    g_main_loop_run(loop);

    g_print("Returned, stopping playback\n");
    gst_element_set_state(pipeline, GST_STATE_NULL);
    g_print("Deleting pipeline\n");
    gst_object_unref(GST_OBJECT(pipeline));

    return 0;
}
